package com.gof.example.singleton.iodhmore;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Created by zhiyuan on 2018/5/1 21:08.
 * haiming.fei@tongdun.cn
 */
public class LoadBalancer {

    private LoadBalancer() {
        //no instance
    }

    public static LoadBalancer getInstance() {
        return LoadBalancerHolder.newObj();
    }

    public static List<LoadBalancer> getList() {
        return LoadBalancerHolder.loadBalancers;
    }

    private static class LoadBalancerHolder {
        private static final int MAX = 3;
        private static Object object = new Object();
        private volatile static List<LoadBalancer> loadBalancers = new ArrayList<>();

        private static LoadBalancer newObj() {
            int size = loadBalancers.size();
            synchronized (object) {
                if (size < MAX) {
                    LoadBalancer balancer = new LoadBalancer();
                    loadBalancers.add(balancer);
                    return balancer;
                } else {
                    return loadBalancers.get(MAX - 1);
                }
            }
        }
    }
}
